package com.zmn.oms.admin.controller.work.list;

import com.alibaba.fastjson.JSON;
import com.google.common.collect.Lists;
import com.zmn.common.constant.GlobalConsts;
import com.zmn.common.dto2.ResponseDTO;
import com.zmn.common.utils.collection.CollectionUtil;
import com.zmn.common.utils.number.NumberUtil;
import com.zmn.dms.common.dto.coup.dro.batch.CoupBatchFicoDRO;
import com.zmn.dms.common.dto.promotion.dio.PromotionFinanceDIO;
import com.zmn.dms.common.dto.promotion.dro.PromotionFinanceDRO;
import com.zmn.dms.common.enums.DiscountTypeEnums;
import com.zmn.dms.dubbo.constant.DmsDubboConsts;
import com.zmn.dms.dubbo.interfaces.coup.batch.BatchGetRemoteService;
import com.zmn.dms.dubbo.interfaces.prom.PromGetRemoteService;
import com.zmn.oms.admin.controller.OmsBaseController;
import com.zmn.oms.business.interfaces.work.OrderWorkListBService;
import com.zmn.oms.business.interfaces.work.OrderWorkPositionBService;
import com.zmn.oms.common.constant.DiscountConsts;
import com.zmn.oms.common.constant.OrderConsts;
import com.zmn.oms.common.dto.ResultDTO;
import com.zmn.oms.common.vo.KVDict;
import com.zmn.oms.model.entity.detail.OrderDetail;
import com.zmn.oms.model.entity.work.OrderWork;
import com.zmn.oms.model.entity.work.OrderWorkQuery;
import com.zmn.base.oms.common.model.es.orderwork.EsOrderWork;
import com.zmn.base.oms.common.model.es.orderwork.EsOrderWorkContact;
import com.zmn.base.oms.common.model.es.orderwork.EsOrderWorkReview;
import com.zmn.oms.model.vo.warning.ZsWarningVO;
import com.zmn.oms.model.vo.work.OrderWorkPositionVO;
import com.zmn.oms.model.vo.work.ZsOrderWorkVO;
import com.zmn.oms.services.interfaces.detail.OrderDetailService;
import com.zmn.oms.services.interfaces.review.OmsOrderReviewService;
import com.zmn.oms.services.interfaces.work.OrderWorkService;
import com.zmn.oms.zmn.business.interfaces.work.ZsOrderWorkQueryBService;
import com.zmn.pay.common.constant.PayConsts;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * @author sunlife
 * @date:2021/7/13 3:55 下午
 * description: 详情页面子模块查询
 */
@Controller
@RequestMapping("/work")
@Slf4j
public class WorkDetailSubListController extends OmsBaseController {

    @Autowired
    OrderDetailService orderDetailService;
    @Autowired
    OrderWorkPositionBService orderPositionBService;
    @Autowired
    OrderWorkService orderWorkService;
    @Autowired
    OrderWorkListBService orderWorkListBService;
    @Reference(version = DmsDubboConsts.INTERFACE_VERSION, check = false, timeout = 2000)
    PromGetRemoteService promGetRemoteService;
    @Reference(version = DmsDubboConsts.INTERFACE_VERSION, check = false, timeout = 2000)
    BatchGetRemoteService batchGetRemoteService;
    @Autowired
    OmsOrderReviewService omsOrderReviewService;

    /**
     * 工单详情-地图
     */
    @RequestMapping(value = "/detail/map")
    public ModelAndView detailMap(Long orderId, Long workId) {
        ModelAndView mv = new ModelAndView("work/positionMap");
        OrderWorkPositionVO vo = orderPositionBService.getById(workId);

        if (vo == null) {
            vo = new OrderWorkPositionVO();
        }
        if ( vo.getOrderLatitude() == null || vo.getOrderLongitude() == null ) {
            OrderDetail orderDetail = orderDetailService.findOrderDetailByKey(orderId);
            vo.setOrderLongitude(orderDetail.getLongitude());
            vo.setOrderLatitude(orderDetail.getLatitude());
        }

        mv.addObject("position", vo);
        OrderWork orderWork = orderWorkService.findOrderWorkByKey(orderId, workId);
        mv.addObject("orderWrok", orderWork);
        return mv;
    }

    /**
     * 工单详情-优惠分摊
     */
    @RequestMapping(value = "/detail/discountsharing")
    public ModelAndView discountSharing(Integer categ, Integer sourceId) {
        ModelAndView mv = new ModelAndView("work/detailsubmodule/discountsharing");
        List<KVDict<String>> sharingList = Lists.newArrayList();

        try {
            if (NumberUtil.isNotNullOrZero(categ) && NumberUtil.isNotNullOrZero(sourceId)) {
                if (Objects.equals(categ, DiscountTypeEnums.DISCOUNT_RULE_COMMON.getSubType())
                        || Objects.equals(categ, DiscountTypeEnums.DISCOUNT_RULE_ARTIFICIAL.getSubType())
                        || Objects.equals(categ, DiscountTypeEnums.DISCOUNT_ACTIVITY_LATE_COMPENSATE.getSubType())
                        || Objects.equals(categ, DiscountTypeEnums.DISCOUNT_CHANNEL.getSubType())
                        || Objects.equals(categ, DiscountTypeEnums.DISCOUNT_FREE.getSubType())) {
                    PromotionFinanceDIO promotionFinanceDIO = new PromotionFinanceDIO();
                    promotionFinanceDIO.setPromId(sourceId);
                    logger.info("获取促销优惠分摊详情 入参：{}", JSON.toJSONString(promotionFinanceDIO));
                    ResponseDTO<PromotionFinanceDRO> responseDTO = promGetRemoteService.getPromotionFinanceConfig(promotionFinanceDIO);
                    logger.info("获取促销优惠分摊详情 出参：{}", JSON.toJSONString(responseDTO));
                    if (responseDTO.isSuccess()) {
                        PromotionFinanceDRO financeDRO = responseDTO.getData();
                        if (Objects.equals(financeDRO.getCompanyRule(), 1)) {
                            KVDict<String> companyInfo = new KVDict<>();
                            companyInfo.setText("总公司");
                            companyInfo.setValue(financeDRO.getCompanyRatio().toString() + "%");
                            sharingList.add(companyInfo);
                            KVDict<String> ssInfo = new KVDict<>();
                            ssInfo.setText("服务主体");
                            ssInfo.setValue(financeDRO.getSsRatio().toString() + "%");
                            sharingList.add(ssInfo);
                        }
                    }
                } else if (Objects.equals(categ, DiscountTypeEnums.DISCOUNT_COUP_COMMON.getSubType())
                        || Objects.equals(categ, DiscountTypeEnums.DISCOUNT_COUP_VOUCHER.getSubType())
                        || Objects.equals(categ, DiscountTypeEnums.DISCOUNT_COUP_CASH.getSubType())){
                    logger.info("获取批次优惠分摊详情 入参：{}", sourceId);
                    ResponseDTO<CoupBatchFicoDRO> responseDTO = batchGetRemoteService.getCoupBatchFico(sourceId);
                    logger.info("获取批次优惠分摊详情 出参：{}", JSON.toJSONString(responseDTO));
                    if (responseDTO.isSuccess()) {
                        CoupBatchFicoDRO financeDRO = responseDTO.getData();
                        if (Objects.equals(financeDRO.getPlatRule(), 1)) {
                            KVDict<String> companyInfo = new KVDict<>();
                            companyInfo.setText("总公司");
                            companyInfo.setValue(financeDRO.getCompanyRatio().toString());
                            sharingList.add(companyInfo);
                            KVDict<String> ssInfo = new KVDict<>();
                            ssInfo.setText("服务主体");
                            ssInfo.setValue(financeDRO.getSsRatio().toString());
                            sharingList.add(ssInfo);
                        }
                    }
                }
            }
        } catch (Exception e) {
            logger.error("获取优惠规则信息失败", e);
        }
        if (CollectionUtil.isNullOrEmpty(sharingList)){
            KVDict<String> info = new KVDict<>();
            info.setText("平台分摊规则");
            info.setValue("按分润规则分摊");
            sharingList.add(info);
        }

        mv.addObject("sharingList", sharingList);
        return mv;
    }


    /**
     * 工单详情-优惠分摊
     */
    @RequestMapping(value = "/detail/subworklist")
    public ModelAndView discountSharing(@RequestParam(name = "originalId", required = false)Long originalId,
                                        @RequestParam(name = "userId", required = false)Long userId,
                                        @RequestParam(name = "type", required = true) Integer type) {

        ModelAndView mv = new ModelAndView("work/detailsubmodule/subworklist");

        OrderWorkQuery query = new OrderWorkQuery();
        query.setOriginalId(originalId);
        query.setUserId(userId);
        query.setWorkType(Lists.newArrayList(type));
        query.setPageSize(10000);

        List<EsOrderWork> esOrderWorks = orderWorkListBService.listPageOrderWorkByQuery(query);

        List<ZsOrderWorkVO> voList = Lists.newArrayList();
        if (CollectionUtils.isNotEmpty(esOrderWorks)) {
            for (EsOrderWork esOrderWork : esOrderWorks) {
                ZsOrderWorkVO vo = new ZsOrderWorkVO();
                BeanUtils.copyProperties(esOrderWork, vo);
                vo.setWorkId(esOrderWork.getId());
                vo.setBizType(esOrderWork.getBizType());
                vo.setPrepayStatusName(PayConsts.getPayStatusName(esOrderWork.getPrepayStatus()));
                vo.setDepositStatusName(PayConsts.getPayStatusName(esOrderWork.getDepositStatus()));
                vo.setRefundReviewStatusName("无需审核");
                if (CollectionUtil.isNotNullOrEmpty(esOrderWork.getWorkReviewList())) {
                    EsOrderWorkReview esOrderWorkReview = esOrderWork.getWorkReviewList()
                            .stream()
                            .filter(e -> Objects.equals(e.getReviewType(), OrderConsts.OMS_ORDER_REVIEW_REFUND))
                            .findFirst().orElse(null);
                    if (Objects.nonNull(esOrderWorkReview)) {
                        vo.setRefundReviewStatusName(OrderConsts.getOrderWorkReviewStatusName(esOrderWorkReview.getReviewStatus()));
                    }
                }
                voList.add(vo);
            }
        }

        mv.addObject("type", type);
        mv.addObject("workList", JSON.toJSONString(voList));

        return mv;
    }
}
